//
//  SCSharePickerVC.m
//  Shuaiche
//
//  Created by zzs on 2018/8/10.
//  Copyright © 2018年 zzs. All rights reserved.
//

#import "SCSharePickerVC.h"
#import "SCImagePickerView.h"
#import <Masonry.h>
#import "SCShareTextView.h"
#import "Config.h"
#import "User+CoreDataProperties.h"
#import <SDWebImage/SDImageCache.h>
#import "UIImage+Utility.h"
#import "MBProgressHUD+Add.h"
#import "SCHttpManager.h"
#import "NSString+Helper.h"
#import "ShareItem.h"
#import "SCSysHelper.h"
#define maxShareCount 9
@interface SCSharePickerVC ()<SCShareTextViewDelegate>

@property (nonatomic, strong) NSArray<LLImagePickerModel *> *list;
@property (nonatomic, weak) SCShareTextView *shareTextView;
@property (nonatomic, strong) NSArray *selectedImages;
@property (nonatomic, assign) NSInteger testIndex;

@end

@implementation SCSharePickerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupImagePickerView];
    [self setupNext];
    self.navigationItem.title = @"所有图片";
    [self fetchMerchantDetail];
}

- (void)fetchMerchantDetail{
  NSMutableDictionary *param = [NSMutableDictionary dictionary];
  param[kMerchantId] = @([Config sharedConfig].user.merchantId);
  [[SCHttpManager shareInstance] httpGet:@"userprod/merchantMgr/merchantDetail" param:param completion:^(id response, NSError *error){
    if(response){
        [Config sharedConfig].user.provinceName = response[kProvinceName];
        [Config sharedConfig].user.cityName = response[kCityName];
        [Config sharedConfig].user.districtName = response[kDistrictName];
        [Config sharedConfig].user.province = [response[kProvince] intValue];
        [Config sharedConfig].user.city = [response[kCity]intValue];
        [Config sharedConfig].user.district = [response[kDistrict]intValue];
        [Config sharedConfig].user.address = response[kAddress];

        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
    }
  }];
}

- (NSString *)address{
    NSMutableString *address = [[NSMutableString alloc] init];
    if(![NSString SC_isBlankString:[Config sharedConfig].user.provinceName]){
        [address appendString:[Config sharedConfig].user.provinceName];
    }
    if(![NSString SC_isBlankString:[Config sharedConfig].user.cityName]){
        [address appendString:[Config sharedConfig].user.cityName];
    }
    if(![NSString SC_isBlankString:[Config sharedConfig].user.districtName]){
        [address appendString:[Config sharedConfig].user.districtName];
    }
    if(![NSString SC_isBlankString:[Config sharedConfig].user.address]){
        [address appendString:[Config sharedConfig].user.address];
    }
    if(address.length){
        return address;
    }else{
        return nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)setupImagePickerView{
    WEAKSELF
    SCImagePickerView *pickerView = [SCImagePickerView sharePickerViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-(40+10+(kDevice_Is_iPhoneX ? 34:10))) countOfRow:4];
    pickerView.maxSharedNum = maxShareCount;
    pickerView.maxImageSelected = 50;
    [self.view addSubview:pickerView];
    pickerView.type = LLImageTypePhotoAndCamera;
    pickerView.allowPickingVideo = NO;
    [pickerView observeSelectedMediaArray:^(NSArray<LLImagePickerModel *> *list) {
        weakSelf.list = list;
    }];
    pickerView.observerdSharedImages = ^(NSArray *sharedImages) {
        weakSelf.selectedImages = sharedImages;
    };
    pickerView.preShowMedias = self.preShows;
}

- (void)setupNext{
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:nextBtn];
    nextBtn.layer.cornerRadius = 4.f;
    [nextBtn setBackgroundColor:SCColor(0xFCDF4B)];
    [nextBtn setTitle:@"保存本地并分享" forState:UIControlStateNormal];
    [nextBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(shareImages) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(280);
        make.height.mas_equalTo(40);
        make.centerX.equalTo(self.view);
      make.bottom.equalTo(self.view.mas_bottom).offset(kDevice_Is_iPhoneX ? -34:-10);
    }];
}

- (void)saveImages{
    WEAKSELF
    [MBProgressHUD showMessage:@"保存中..." toView:self.view];
    NSMutableArray *selectedImages = [[NSMutableArray alloc] init];
    [self.list enumerateObjectsUsingBlock:^(LLImagePickerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if(obj.isSelected){
            [selectedImages addObject:obj];
        }
    }];
    NSMutableArray *sharedArray = [NSMutableArray array];
    [selectedImages enumerateObjectsUsingBlock:^(LLImagePickerModel * model, NSUInteger idx, BOOL * _Nonnull stop) {
        [self handleModel:model toArray:sharedArray atIndex:idx];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:weakSelf.view animated:NO];
        [MBProgressHUD showSuccess:@"已保存到相册" toView:nil];
        if (weakSelf.shareContents.count > 0) {
          [weakSelf showShareTextView];
        }
    });
 
}

- (void)shareImages{
    WEAKSELF
    NSMutableArray *selectedImages = [[NSMutableArray alloc] init];
    [self.list enumerateObjectsUsingBlock:^(LLImagePickerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if(obj.isSelected){
            [selectedImages addObject:obj];
        }
    }];
        if(!selectedImages.count){
            [MBProgressHUD showError:@"请选择车辆图片!" toView:nil];
            return;
        }
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if(status==PHAuthorizationStatusNotDetermined){
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if(status==PHAuthorizationStatusAuthorized){
                dispatch_async(dispatch_get_main_queue(), ^{
                     [weakSelf saveImages];
                });
            }
        }];
    }else if (status==PHAuthorizationStatusDenied){
        [MBProgressHUD showError:@"请在iPhone的设置-隐私-照片中,允许帅车内采访客相册" toView:nil];
    }else if(status == PHAuthorizationStatusAuthorized){
          [self saveImages];
    }
    else{
      
    }
}

- (void)showShareTextView{
    if(![Config sharedConfig].user.merchantId){
        [SCSysHelper openWeChat];
        return;
    }
    SCShareTextView *shareTextView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([SCShareTextView class]) owner:nil options:nil][0];
    [shareTextView setFrame:[UIScreen mainScreen].bounds];
    shareTextView.delegate = self;
    NSMutableArray *labels = [NSMutableArray array];
    [self.shareContents enumerateObjectsUsingBlock:^(NSString *content, NSUInteger idx, BOOL * _Nonnull stop) {
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = self.shareContents[idx];
        label.font = [UIFont systemFontOfSize:12];
        [labels addObject:label];
        [shareTextView.shareContentBg addSubview:label];
    }];
    [labels enumerateObjectsUsingBlock:^(UILabel *label, NSUInteger idx, BOOL * _Nonnull stop) {
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            UIView *previousView = nil;
            if(idx>0){
                previousView = labels[idx-1];
            }
            if(previousView){
                make.top.equalTo(previousView.mas_bottom).offset(12);
            }
            make.leading.equalTo(shareTextView.shareContentBg.mas_leading).offset(16);
            make.trailing.equalTo(shareTextView.shareContentBg.mas_trailing).offset(-16);
            if(idx == 0){
                make.top.equalTo(shareTextView.shareContentBg.mas_top).offset(90);
            }
        }];
    }];
    [self.view addSubview:shareTextView];
    self.shareTextView = shareTextView;
}

- (void)openWX{
    [SCSysHelper openWeChat];
}

#pragma mark -
#pragma mark - ShareTextViewDelegate

- (void)shareTextViewDidClickNoCopy:(SCShareTextView *)shareTextView{
    [shareTextView removeFromSuperview];
    [self openWX];
}

- (void)shareTextViewDidClickCopy:(SCShareTextView *)shareTextView{
    [shareTextView removeFromSuperview];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    NSMutableString *contents = [[NSMutableString alloc] init];
    [self.shareContents enumerateObjectsUsingBlock:^(NSString *content, NSUInteger idx, BOOL * _Nonnull stop) {
        if(idx ==0){
            [contents appendString:content];
        }else{
            [contents appendString:@"\n"];
            [contents appendString:content];
        }
    }];
    [pasteboard setString:contents];
    [self openWX];
}


- (void)shareTextViewDidClickClose:(SCShareTextView *)shareTextView{
    [shareTextView removeFromSuperview];
}

#pragma mark -
#pragma mark - Share
- (NSData *)dataForImage:(UIImage *)image{
   // image = [UIImage compressedImage:image compressionQualityForJPG:1. compressibilitySize:1080];
    int alphaInfo = CGImageGetAlphaInfo(image.CGImage);
    BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone ||
                      alphaInfo == kCGImageAlphaNoneSkipFirst ||
                      alphaInfo == kCGImageAlphaNoneSkipLast);
    BOOL imageIsPng = hasAlpha;
    NSData *data = nil;
    if (imageIsPng) {
        data = UIImagePNGRepresentation(image);
    }
    else {
        data = UIImageJPEGRepresentation(image, (CGFloat)1.0);
    }
    return data;
}

- (void)handleModel:(LLImagePickerModel *)model toArray:(NSMutableArray *)sharedArray atIndex:(NSInteger)index{

    if(model.image){
        [Config savePhotoToCustomAlbumWithName:nil photo:model.image];
    }else if(model.imageUrlString){
        if([[SDImageCache sharedImageCache] imageFromMemoryCacheForKey:model.imageUrlString]){
            [Config savePhotoToCustomAlbumWithName:nil photo:[[SDImageCache sharedImageCache] imageFromMemoryCacheForKey:model.imageUrlString]];
        }else if([[SDImageCache sharedImageCache] imageFromDiskCacheForKey:model.imageUrlString]){
            [Config savePhotoToCustomAlbumWithName:nil photo:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:model.imageUrlString]];
        }else{

        }
    }
}

- (void)showShare{
    if(self.onlySharePictures){
        NSMutableArray *selectedImages = [[NSMutableArray alloc] init];
        [self.list enumerateObjectsUsingBlock:^(LLImagePickerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if(obj.isSelected){
                [selectedImages addObject:obj];
            }
        }];
        NSMutableArray *sharedArray = [NSMutableArray array];
        [selectedImages enumerateObjectsUsingBlock:^(LLImagePickerModel * model, NSUInteger idx, BOOL * _Nonnull stop) {
            [self handleModel:model toArray:sharedArray atIndex:idx];
        }];
        WEAKSELF
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:weakSelf.view animated:NO];
            [self openWX];
        });
        return;
    }
}
@end
